import sys
sys.path.append("../../")
from sentiDataReader import Senti_domain_map
from metrics import precision_recall_fscore_support
from model import VanillaBert, accuracy_score
import fitlog, os, pickle, random, numpy as np
from tqdm import trange
from Senti_Utils import obtain_model, obtain_CRST_set, reconfig_args, CRST_Dataset
import torch, torch.nn.functional as F

class SelfTrainingUtils:
    def __init__(self, random_seed):
        self.seed = random_seed

    def acc_P_R_F1(self, y_true, y_pred):
        return accuracy_score(y_true, y_pred.cpu()), \
                    precision_recall_fscore_support(y_true, y_pred.cpu())

    def dataIter(self, pseudo_set, labeled_target=None, batch_size=32):
        p_idxs = list(range(len(pseudo_set))) if not hasattr(pseudo_set, 'valid_indexs') else pseudo_set.valid_indexs
        p_len = len(p_idxs)
        if labeled_target is None:
            l_len = 0
            l_idxs = []
        else:
            l_idxs = list(range(len(labeled_target))) if not hasattr(labeled_target, 'valid_indexs') \
                                                        else labeled_target.valid_indexs
            l_len = len(l_idxs)
        data_size = p_len + l_len
        idxs = random.sample(range(data_size), data_size)*2
        for start_i in range(0, data_size, batch_size):
            batch_idxs = idxs[(start_i):(start_i+batch_size)]
            items = [pseudo_set[p_idxs[idx]] if idx < p_len else \
                        labeled_target[l_idxs[idx-p_len]] for idx in batch_idxs]
            yield pseudo_set.collate_raw_batch(items)

    def Batch2Vecs(self, model: VanillaBert, batch):
        if batch[0].device != model.device:  # data is on a different device
            input_ids, masks, seg_ids = batch[0].to(model.device), \
                                        batch[1].to(model.device), \
                                        batch[2].to(model.device)
        else:
            input_ids, masks, seg_ids = batch[0], batch[1], batch[2]
        encoder_dict = model.bert.bert.forward(
            input_ids=input_ids,
            attention_mask=masks,
            token_type_ids=seg_ids
        )
        return encoder_dict.pooler_output

    def AugBatch2Vecs(self, model:VanillaBert, batch):
        rand = random.random()
        if rand < 0.2:
            model.bert.bert.embeddings.aug_type = "gaussian"
        elif rand < 0.4:
            model.bert.bert.embeddings.aug_type = "g_blur"
        elif rand < 0.6:
            model.bert.bert.embeddings.aug_type = None
            loss, acc = model.lossAndAcc(batch)
            loss.backward()
            model.bert.bert.embeddings.aug_type = "adver"
        elif rand < 0.8:
            model.bert.bert.embeddings.aug_type = "rMask"
        else:
            model.bert.bert.embeddings.aug_type = "rReplace"
        return self.Batch2Vecs(model, batch)

    def lossAndAcc(self, model:VanillaBert, batch, temperature=1.0):
        pooledOutput = self.Batch2Vecs(model, batch)
        logits = model.bert.classifier(pooledOutput)
        preds = F.softmax(logits / temperature, dim=1)
        epsilon = torch.ones_like(preds) * 1e-8
        preds = (preds - epsilon).abs()  # to avoid the prediction [1.0, 0.0], which leads to the 'nan' value in log operation
        labels = batch[-2].to(preds.device)
        labels = labels.argmax(dim=1) if labels.dim() == 2 else labels
        loss = F.nll_loss(preds.log(), labels)
        acc = accuracy_score(labels.cpu().numpy(), preds.argmax(dim=1).cpu().numpy())
        return loss, acc

    def dataset_logits(self, model:VanillaBert, data, idxs=None, batch_size=40):
        preds = []
        if idxs is None:
            idxs = list(range(len(data)))
        for i in trange(0, len(idxs), batch_size):
            batch_idxs = idxs[i:min(len(idxs), i + batch_size)]
            batch = data.collate_raw_batch([data[idx] for idx in batch_idxs])
            pred = model.predict(batch, temperature=1.0)
            preds.append(pred)
        pred_tensor = torch.cat(preds)
        return pred_tensor

    def dataset_inference(self, model:VanillaBert, data, idxs=None, batch_size=20):
        pred_tensor = self.dataset_logits(model, data, idxs, batch_size)
        vals, idxs = pred_tensor.sort(dim=1)
        return idxs[:, -1], vals[:, -1]

    def augPredict(self, model, batch):
        rand = random.random()
        if rand < 0.2:
            model.bert.bert.embeddings.aug_type = "gaussian"
        elif rand < 0.4:
            model.bert.bert.embeddings.aug_type = "g_blur"
        elif rand < 0.6:
            model.bert.bert.embeddings.aug_type = None
            loss, acc = model.lossAndAcc(batch)
            loss.backward()
            model.bert.bert.embeddings.aug_type = "adver"
        elif rand < 0.8:
            model.bert.bert.embeddings.aug_type = "rMask"
        else:
            model.bert.bert.embeddings.aug_type = "rReplace"
        preds = model.predict(batch)
        return preds

    def perf(self, model:VanillaBert, data, label, idxs=None, batch_size=20):
        with torch.no_grad():
            y_pred, _ = self.dataset_inference(model, data, idxs=idxs, batch_size=batch_size)
        label = label[idxs] if idxs is not None else label
        y_true = label if label.dim() == 1 else label.argmax(dim=1)
        return self.acc_P_R_F1(y_true, y_pred)

class SelfTrainingBase(SelfTrainingUtils):
    def __init__(self, random_seed, log_dir, suffix, model_file, class_num, learning_rate):
        super(SelfTrainingBase, self).__init__(random_seed)
        if not os.path.exists(log_dir):
            os.system("mkdir {}".format(log_dir))
        fitlog.set_log_dir("{}/".format(log_dir), new_log=True)
        self.log_dir = log_dir
        self.suffix = suffix
        self.model_file = model_file
        self.best_valid_acc = 0.0
        self.min_valid_loss = 1e8
        self.class_num = class_num
        self.valid_step = 0
        self.learning_rate = learning_rate

    def obtainOptim(self, model):
        optimizerGroupedParameters = [
                                         {'params': p,
                                          'lr': self.learning_rate * pow(0.8, 12 - int(
                                              n.split("layer.")[1].split(".", 1)[0])) if "layer." in n \
                                              else (self.learning_rate * pow(0.8, 13) if "embedding" in n else self.learning_rate)
                                          # layer-wise fine-tuning
                                          } for n, p in model.named_parameters()
                                     ]
        optim = torch.optim.Adam(optimizerGroupedParameters)
        return optim

    def annotate(self, model: VanillaBert, data:CRST_Dataset, pseaudo_idxs=[], batch_size=20):
        c_idxs = list(set(range(len(data))) - set(pseaudo_idxs))
        with torch.no_grad():
            pred_tensor = self.dataset_logits(model, data, idxs=c_idxs, batch_size=batch_size)
            weak_label = (pred_tensor > 0.5).long().tolist()
            data.setLabel(weak_label, c_idxs)

    def dataSelection(self, pseudo_set):
        assert hasattr(pseudo_set, "logits")

    def modelTrain(self, max_epoch, tr_model, train_set, valid_set, extra_train=None,
                   suffix='train', best_valid_acc= -1.0, batch_size=32, threshold=0.2):
        valid_acc = best_valid_acc if best_valid_acc != -1 else self.best_valid_acc
        loss_list = []
        tmp_model_file = "{}/{}_tmp.pkl".format(self.log_dir, suffix)
        optim = self.obtainOptim(tr_model)
        for epoch in range(max_epoch):
            for step, batch in enumerate(self.dataIter(train_set, extra_train, batch_size=batch_size)):
                loss, acc = self.lossAndAcc(tr_model, batch)
                optim.zero_grad()
                loss.backward()
                optim.step()
                torch.cuda.empty_cache()
                print('####Model Update#### step={} ({} | {}) ####, loss = {}'.format(
                    step, epoch, max_epoch, loss.data.item()
                ))
                loss_list.append(loss.data.item())
            mean_loss = np.mean(loss_list)
            loss_list = []
            print("========> mean loss:", mean_loss)

            rst = self.perf(tr_model, valid_set, valid_set.labelTensor())
            acc_v, (p_v, r_v, f1_v, _) = rst
            output_items = [("valid_acc", acc_v)] + \
                           [('valid_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                           [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                           [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
            print("valid perf:", rst)
            fitlog.add_metric({f"ValidPerf_{suffix}": dict(output_items)}, step=self.valid_step)
            self.valid_step += 1

            if acc_v > valid_acc:
                valid_acc = acc_v
                torch.save(tr_model.state_dict(), tmp_model_file)
            if mean_loss < threshold:  # early stop
                break
        if os.path.exists(tmp_model_file):
            tr_model.load_state_dict(torch.load(tmp_model_file))
            os.system("rm {}".format(tmp_model_file))
        return valid_acc, tmp_model_file

    def initTrainingEnv(self, model, labeled_source, valid_target, test_set, test_label, isWeightInited=False):
        if not isWeightInited:
            self.modelTrain(10, model, labeled_source, valid_target, best_valid_acc=0.0)
            rst_model = self.perf(model, test_set, test_label)
            acc_v, (p_v, r_v, f1_v, _) = rst_model
            print(f"Original Performance of {self.suffix}:", rst_model)
            output_items = [("valid_acc", acc_v)] + \
                           [('valid_prec_{}'.format(i), p_v[i])  for i in range(self.class_num)] + \
                           [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                           [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
            fitlog.add_best_metric({f"Original_{self.suffix}": dict(output_items)})
        random.seed(self.seed)
        np.random.seed(self.seed)
        torch.manual_seed(self.seed)
        torch.cuda.manual_seed_all(self.seed)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False
        self.best_valid_acc = 0.0
        self.min_valid_loss = 1e8

    def trainning(self, model, labeled_source, labeled_target, unlabeled_target, valid_set, test_set,
                  test_label=None, max_iterate=100, isWeightInited=False):
        self.initTrainingEnv(model, labeled_source, valid_set, test_set, test_label, isWeightInited)
        for iterate in range(max_iterate):
            self.annotate(model, unlabeled_target)
            self.dataSelection(unlabeled_target)
            val_acc, model_file = self.modelTrain(1, model, unlabeled_target, valid_set,
                                                    extra_train=labeled_target)
            if val_acc > self.best_valid_acc:
                self.best_valid_acc = val_acc
                self.logPerf(model, test_set, test_label, self.suffix)

    def logPerf(self, model, test_set, test_label, test_suffix, step=0):
        rst_model = self.perf(model, test_set, test_label)
        acc_v, (p_v, r_v, f1_v, _) = rst_model
        print("BestPerf : ".format(step), rst_model)
        output_items = [("valid_acc", acc_v)] + \
                       [('valid_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                       [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                       [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
        fitlog.add_best_metric({f"BestPerf_{test_suffix}": dict(output_items)})

class CRST_LRENT(SelfTrainingBase):
    def __init__(self, random_seed, log_dir, suffix, model_file, class_num,
                    learning_rate=5e-5, alpha=0.1, topK=0.2):
        super(CRST_LRENT, self).__init__(random_seed, log_dir, suffix, model_file, class_num, learning_rate)
        self.alpha = alpha
        self.topK = topK

    def annotate(self, model: VanillaBert, data:CRST_Dataset, pseaudo_idxs=[], batch_size=20):
        c_idxs = list(set(range(len(data))) - set(pseaudo_idxs))
        with torch.no_grad():
            pred_tensor = self.dataset_logits(model, data, idxs=c_idxs, batch_size=batch_size)
            if not hasattr(data, "logits"):
                data.logits = torch.zeros([len(data), self.class_num], device=pred_tensor.device)
            data.logits[c_idxs] = pred_tensor
        topk_vals, _ = pred_tensor.topk(int(self.topK*len(pred_tensor)), dim=0)
        self.lambda_k = topk_vals[-1]
        pseudo_label = (pred_tensor/self.lambda_k).pow(1.0/self.alpha)
        pseudo_label = (pseudo_label/(pseudo_label.sum(dim=1).unsqueeze(-1))).tolist()
        data.setLabel(pseudo_label, c_idxs)

    def dataSelection(self, pseudo_set):
        assert hasattr(pseudo_set, "logits")
        _, indexs = pseudo_set.logits.topk(int(len(pseudo_set)*self.topK), dim=0)
        pseudo_set.valid_indexs = indexs.reshape([-1]).tolist()

if __name__ == "__main__":
    with open("../../args.pkl", 'rb') as fr:
        argConfig = pickle.load(fr)
    # argConfig.model_dir = str(__file__).rstrip(".py")
    argConfig.model_dir = './tmp'
    # Set all the seeds
    seed = argConfig.seed
    reconfig_args(argConfig)

    # See if CUDA available
    device = torch.device("cpu") if not torch.cuda.is_available() else torch.device("cuda:0")

    domainID = 2
    fewShotCnt = 100
    SentiDomainList = list(Senti_domain_map.keys())
    newDomainName = SentiDomainList[domainID-1]

    model1, tokenizer = obtain_model(args=argConfig, model_device=device)
    labeledSource, validTarget, testTarget, labeledTarget, unlabeledTarget = obtain_CRST_set(newDomainName,
                                                                                               tokenizer_M=tokenizer,
                                                                                               lt_count=0)
    trainer = CRST_LRENT(seed, argConfig.model_dir,
                         "{}_FS{}".format(newDomainName, fewShotCnt),
                         "{}/model_{}.pth".format(argConfig.model_dir, newDomainName),
                         class_num=2, learning_rate=2e-5, alpha=0.1, topK=0.4)
    trainer.trainning(model1, labeledSource, labeledTarget, unlabeledTarget,
                      validTarget, testTarget, testTarget.labelTensor().clone(),
                      max_iterate=100, isWeightInited=False)
